<script setup>
import { ref } from 'vue'
import { addArticle } from '@/api/article'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()
const title = ref('')
const content = ref('')
const images = ref([])
const tags = ref('')
const type = ref(0)
const location = ref('')
const showTimePicker = ref(false)
const publishTime = ref('')
const newTag = ref('')
const fileList = ref([])

const onSubmit = async () => {
  if (!title.value.trim()) {
    showToast('请输入标题')
    return
  }
  if (!content.value.trim()) {
    showToast('请输入内容')
    return
  }
  if (images.value.length === 0) {
    showToast('请至少上传一张图片')
    return
  }

  try {
    const data = {
      title: title.value,
      content: content.value,
      images: images.value.join(','),
      tag: tags.value,
      type: type.value,
      location: location.value,
      publishTime: publishTime.value || null
    }
    await addArticle(data)
    showToast('发布成功')
    router.push('/')
  } catch (error) {
    showToast('发布失败')
  }
}

const afterRead = async (file) => {
  const formData = new FormData()
  formData.append('file', file.file)
  
  try {
    const res = await request({
      url: '/oss/uploadArticle',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data) {
      images.value.push(res.data)
      file.url = res.data
    } else {
      showToast('图片上传失败')
    }
  } catch (error) {
    showToast('图片上传失败')
  }
}

const deleteImage = (file) => {
  const index = fileList.value.indexOf(file)
  if (index > -1) {
    images.value.splice(index, 1)
  }
}

const addTag = (tag) => {
  if (tag) {
    if (tags.value) {
      tags.value += `#${tag}`
    } else {
      tags.value = `#${tag}`
    }
    newTag.value = ''
  }
}
</script>

<template>
  <div class="post-page">
    <van-nav-bar
      title="发布文章"
      left-arrow
      @click-left="$router.back()"
    />
    
    <div class="form">
      <van-field
        v-model="title"
        label="标题"
        placeholder="请输入标题"
      />

      <van-field
        v-model="content"
        label="内容"
        type="textarea"
        placeholder="请输入内容"
        :autosize="{ minHeight: 100 }"
      />

      <div class="upload-section">
        <van-uploader
          v-model="fileList"
          :after-read="afterRead"
          multiple
          :max-count="9"
          @delete="deleteImage"
        />
      </div>

      <div class="type-select">
        <van-radio-group v-model="type" direction="horizontal">
          <van-radio :name="0">游记</van-radio>
          <van-radio :name="1">攻略</van-radio>
        </van-radio-group>
      </div>

      <div class="tags">
        <van-field
          v-model="newTag"
          label="标签"
          placeholder="输入标签后点击添加"
        >
          <template #button>
            <van-button size="small" type="primary" @click="addTag(newTag)">添加</van-button>
          </template>
        </van-field>
        <div class="tag-preview">{{ tags }}</div>
      </div>

      <van-field
        v-model="publishTime"
        label="定时发布"
        placeholder="请输入发布时间（可选，格式：2024-01-01 12:00:00）"
      />
    </div>

    <div class="submit">
      <van-button type="primary" block @click="onSubmit">发布</van-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.post-page {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 80px;

  .form {
    background: #fff;
    margin-top: 10px;
    padding: 15px;
  }

  .upload-section {
    padding: 15px 0;
  }

  .type-select {
    padding: 10px 16px;
  }

  .tags {
    .tag-preview {
      padding: 10px 16px;
      color: #666;
      font-size: 14px;
      word-break: break-all;
    }
  }

  .submit {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background: #fff;
  }
}
</style> 